<!doctype html>
<html>
<head>
  <title>微信授权登录</title>
  <meta charset="utf-8">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <meta http-equiv="pragma" content="no-cache">
  <script src="//cdn.bootcss.com/axios/0.16.1/axios.min.js"></script>
  <script>
  var WX = {
    config: {
      appid: 'wx9f2c98afbbbbcc03', // 微信appid
      scope: 'snsapi_base', // 微信应用授权作用域'snsapi_base' 或 'snsapi_userinfo'
      expira: 0 // token过期时间（毫秒），0表示每次进入页面都更新token
    },
    storageName: {
      token: 'token', // 需要设置的token名称
      tokenCreateAt: '__WX_auth_token_create_at', // token的创建时间
      fullPath: 'full_path' //hash后面的部分，如：/home/index
    },
    getParam: function (name, url) { // 获取url参数
      if (!url) url = window.location.href;
      name = name.replace(/[\[\]]/g, '\\$&');
      var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
          results = regex.exec(url);
      if (!results) return null;
      if (!results[2]) return '';
      return decodeURIComponent(results[2].replace(/\+/g, ' '));
    },
    redirect: function () {
      var token = window.localStorage.getItem(WX.storageName.token);
      var tokenCreateAt = window.localStorage.getItem(WX.storageName.tokenCreateAt);
      if (token && Date.parse(new Date()) - tokenCreateAt <= WX.config.expira) { // token存在也未过期，跳转到实际需要登录的页面
        window.location.replace(WX.getParam('redirect_uri') || '/');
      } else { // token不存在或过期，获取token
        var code = WX.getParam('code');
        if (code) { // code存在，去服务端交换token
          axios.post('/WebAPI/API/Authentication/GetWeiXinToken', {
              code: code,
              phoneNumber: "15062503567",
              appid: "wx9f2c98afbbbbcc03",
              secret: "0c0a91170dabd08566aafb2f646a28fa",
          }).then(function (res) {
              console.log(res);
            window.localStorage.setItem(WX.storageName.token, res.data.openid);
            window.localStorage.setItem(WX.storageName.tokenCreateAt, Date.parse(new Date()));

            let redirectUri = WX.getParam('redirect_uri');
            var Token = res.data.data.Token;
            var UserName = res.data.data.UserName;
                        var UserGuid = res.data.data.UserGuid;
                        // if (redirectUri.indexOf("?") >= 0) {
                            // window.location.href = redirectUri + "&token=" + Token + "&uid=" + username + "&token=" + UserName;
                        // }else {
                            window.location.href = redirectUri + "?token=" + Token + "&uid=" + UserGuid + "&username=" + UserName;
                        // }

          }, function (err) {
            // 调用接口失败可以调用微信的js-sdk的closeWindow方法关闭浏览器窗口
            window.alert('微信授权失败');
          });
        } else { // code不存在，跳转到获取code页面
          var fullPath = WX.getParam('full_path');
          if (fullPath) window.localStorage.setItem(WX.storageName.fullPath, fullPath);
          window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize' +
                                 '?appid=' + WX.config.appid +
                                 '&redirect_uri=' + encodeURIComponent(window.location.href) +
                                 '&response_type=code' +
                                 '&scope=' + WX.config.scope +
                                 '&state=' +
                                 '#wechat_redirect';
        }
      }
    }
  }
  WX.redirect();
  </script>
</head>
</html>